package com.fhzn.auth.entity;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;

import java.io.*;
import java.nio.file.Path;

/**
 * @author fhzn
 */
@Slf4j
public class DeleteAfterReadeFileSystemResource extends FileSystemResource {

    public DeleteAfterReadeFileSystemResource(Path file) {
        super(file);
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new DeleteOnCloseFileInputStream(super.getFile());
    }

    private static final class DeleteOnCloseFileInputStream extends FileInputStream {

        private File file;

        DeleteOnCloseFileInputStream(File file) throws FileNotFoundException {
            super(file);
            this.file = file;
        }

        @Override
        public void close() throws IOException {
            super.close();
            try {
                file.delete();
            } catch (Exception e) {
                log.warn("文件:{} 删除失败", file.getAbsolutePath(), e);
            }
        }
    }
}